package com.smallyu.order.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: small-yu
 * @Package: com.smallyu.order.utils
 * @Project: order
 * @Date: 2024/4/9
 * @Time: 23:19
 */
@Component
public class YuJwtUtils {

    @Value("${smallyu.jwt.secret}")
    private  String secret;

    @Value("${smallyu.jwt.expire}")
    private  Long expire;

    public  String createToken(String username,String password){
        String token = "";
        try {
            Date expireData = new Date(System.currentTimeMillis() + expire * 100000);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            Map<String, Object> header = new HashMap<>();
            header.put("typ","JWT");
            header.put("alg","SH256");
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("username", username)
                    .withClaim("password", password)
                    .withExpiresAt(expireData)
                    .sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }

    public  boolean verifyToken(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT verify = verifier.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }
}
